'use strict';

const express = require('express');
const request = require('request');
const cookieParser = require('cookie-parser');  

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();

app.use(express.urlencoded({extended: true}))
app.use(cookieParser()); 
app.use(express.json())

// view engine setup
app.set('views', './views');
app.engine('.html', require('ejs').__express);
app.set('view engine', 'html')



app.get('/', (req, res) => {
  res.render('welcome', { 

  });
})
// var url="请求url"; 

app.get('/register', (req, res) => {
  res.render('register')
})

app.get('/login', (req, res) => {
  res.render('login')
})

app.get('/jwt', (req, res) => {
  res.render('jwt')
})

app.get('/dorm', (req, res) => {
  res.send('选宿舍（待完善）')
})

app.post('/register', (req, res) => {
  console.log('post register')
  console.log(req.body.username)
  res.send(req.body.password)
})


// var register_url = "http://localhost:8099/user/register"
// var login_url = "http://localhost:8099/user/login"
// var jwt_url = "http://localhost:8098/verify"
var register_url = "http://register:8090/user/register"
var login_url = "http://login:8099/user/login"
var jwt_url = "http://jwt:8098/verify"
var requestData= JSON.stringify({
  username: '15623301903',
  password: 'password'
}); 

app.get('/jwt/verify', (req, res) => {
  request.post({
    url: jwt_url, 
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded", }, 
    form:{
      token: req.cookies.token
    }
  }, function(error, response, body) {
    console.log(body)
    var json_obj= eval('(' + body + ')'); 
    console.log(json_obj.authenticated)

    if (!error && response.statusCode == 200 && json_obj.authenticated) {// 请求成功的处理逻辑
      res.render('index', { 
        title: 'Success',
        content: '验证通过'
      });
    } else {
      res.render('index', { 
        title: 'Fail',
        content: '验证不通过:'
      });
    }
  }); 
  // res.send('Hello World');
});


app.post('/user/register', (req, res) => {
  request.post({
    url: register_url, 
    method: "POST",
    headers: { "content-type": "application/json", }, 
    body: JSON.stringify({
      username: req.body.username,
      password: req.body.password
    })
  }, function(error, response, body) {
    console.log(body)
    var json_obj= eval('(' + body + ')'); 
    console.log(json_obj.status)

    if (!error && response.statusCode == 200 && json_obj.status == 1) {// 请求成功的处理逻辑
      res.render('index', { 
        title: 'Success',
        content: '注册成功'
      });

    } else {
      res.render('index', { 
        title: 'Fail',
        content: '注册失败:' + json_obj.message
      });
    }
  }); 
  // res.send('Hello World');
});

app.post('/user/login', (req, res) => {
  request.post({
    url: login_url, 
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded", }, 
    form:{
      username: req.body.username,
      password: req.body.password
    }
  }, function(error, response, body) {
    console.log(body)
    var json_obj= eval('(' + body + ')'); 
    console.log(json_obj.status)
    console.log(json_obj.token)

    if (!error && response.statusCode == 200 && json_obj.status == 1) {// 请求成功的处理逻辑
      res.cookie("token",json_obj.token,{maxAge: 900000, httpOnly: true});  

      res.render('index', { 
        title: 'Success',
        content: '登录成功'
      });
    } else {
      res.render('index', { 
        title: 'Fail',
        content: '登录失败:'
      });
    }
  }); 
  // res.send('Hello World');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);